<template>
    <div class="sales-dashboard">
        <h1>采购数据仪表板</h1>

        <!-- 第一行：销售趋势图和产品销售柱状图 -->
        <div class="chart-row">
            <div class="chart-card">
                <div ref="trendChartRef" class="chart-container"></div>
            </div>
            <div class="chart-card">
                <div ref="productChartRef" class="chart-container"></div>
            </div>
        </div>

        <!-- 第二行：销售渠道占比 -->
        <div class="chart-row">
            <div class="chart-card">
                <div ref="channelChartRef" class="chart-container"></div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

// DOM refs
const trendChartRef = ref(null);
const productChartRef = ref(null);
const channelChartRef = ref(null);

// ECharts 实例
let trendChart = null;
let productChart = null;
let channelChart = null;

// 初始化所有图表
const initAllCharts = async () => {
    if (trendChartRef.value) {
        trendChart = echarts.init(trendChartRef.value);
        trendChart.setOption(getTrendChartOption());
        await getTrendData();
        updateTrendChart()
    }

    if (productChartRef.value) {
        productChart = echarts.init(productChartRef.value);
        productChart.setOption(getProductChartOption());
        await getGoodsProcurementAmountList()
        updateProductChartOption()
    }

    if (channelChartRef.value) {
        channelChart = echarts.init(channelChartRef.value);
        channelChart.setOption(getChannelChartOption());
        await getSupplierAmountPercentage()
        updateSupplierAmountPercentage()
    }

    window.addEventListener('resize', handleResize);
};

// 响应窗口大小变化
const handleResize = () => {
    trendChart?.resize();
    productChart?.resize();
    channelChart?.resize();
};

// 销毁图表实例
const disposeCharts = () => {
    trendChart?.dispose();
    productChart?.dispose();
    channelChart?.dispose();
    window.removeEventListener('resize', handleResize);
};

// 图表配置项
const getTrendChartOption = () => ({
    title: { text: '月度采购趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 元' }
    },
    series: [{
        name: '采购额',
        data: [120, 132, 101, 134, 90, 230],
        type: 'line',
        smooth: true,
        itemStyle: { color: '#409EFF' },
        areaStyle: { opacity: 0.3 }
    }]
});
//获取月度采购趋势数据
const monthTrendData = ref([])

const getTrendData = async () => {
    const params = {
        companyCode: ''
    }
    const res = await axios.get('/lxw/getMonthTrend', { params })
    console.log("月度采购趋势数据", res.data)
    if (res.data.code == 5200) {
        monthTrendData.value = res.data.monthTrend
    }
};
// 更新月度采购趋势图
const updateTrendChart = () => {
    if (monthTrendData.value.length > 0) {
        const months = monthTrendData.value.map(item => `${item.month}月`);
        const amounts = monthTrendData.value.map(item => item.totalSales);
        console.log("xxx", months, amounts)
        trendChart.setOption({
            xAxis: {
                data: months.length > 0 ? months : ['1月', '2月', '3月', '4月', '5月', '6月']
            },
            series: [{
                data: amounts
            }]
        });
    }
};

const getProductChartOption = () => ({
    title: { text: '产品采购对比', left: 'center' },
    tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
    },
    xAxis: {
        type: 'category',
        data: ['产品A', '产品B', '产品C', '产品D', '产品E']
    },
    yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 件' }
    },
    series: [{
        name: '采购量',
        data: [120, 200, 150, 80, 70],
        type: 'bar',
        itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
            ])
        }
    }]
});
//获取产品采购对比数据
const goodsProcurementAmountList = ref([])
const getGoodsProcurementAmountList = async () => {
    const params = {
        companyCode: ''
    }
    const res = await axios.get('/lxw/getProcurementGoodsAmount', { params })
    console.log("产品采购对比数据", res.data)
    if (res.data.code == 5200) {
        goodsProcurementAmountList.value = res.data.goodsAmount
    }
};
//更新产品采购对比
const updateProductChartOption = () => {
    if (goodsProcurementAmountList.value.length > 0) {
        const products = goodsProcurementAmountList.value.map(item => item.productName);
        const quantitys = goodsProcurementAmountList.value.map(item => item.totalQuantity);
        productChart.setOption({
            xAxis: {
                data: products.length > 0 ? products : [],
                axisLabel: {
                    interval: 0, // 强制显示所有标签
                    rotate: 30,  // 如果标签太长可以旋转30度
                    margin: 10,  // 标签与坐标轴的间距
                    // 如果标签文字太长可以截断并显示省略号
                    formatter: function (value) {
                        return value.length > 6 ? value.substring(0, 6) + '...' : value;
                    }
                }
            },
            series: [{
                data: quantitys
            }]
        });
    }
};

const getChannelChartOption = () => ({
    title: { text: '采购供应商金额占比', left: 'center' },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [{
        name: '采购供应商',
        type: 'pie',
        radius: '50%',
        data: [
            { value: 1048, name: '供货商1' },
            { value: 735, name: '供货商2' },
            { value: 580, name: '供货商3' },
            { value: 484, name: '供货商4' }
        ],
        emphasis: {
            itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
        }
    }]
});

//获取供应商采购金额占比
const supplierAmountPercentage = ref([
])

const getSupplierAmountPercentage = async() => {
    const params = {
        companyCode:''
    }
    const res = await axios.get('/api/procurement/getSupplierData',{params})
    console.log("供应商采购金额占比",res.data)
    if(res.data.code ==5200){
        supplierAmountPercentage.value = res.data.supplierData
    }
}
//更新供应商采购金额占比
const updateSupplierAmountPercentage = () => {
    if(supplierAmountPercentage.value.length > 0){
        const pieData = supplierAmountPercentage.value.map(item => ({
            value: item.totalAmount,
            name: item.supplierName
        }))
        
        channelChart.setOption({
            legend: {
                data: supplierAmountPercentage.value.map(item => item.supplierName)
            },
            series: [{
                data: pieData
            }]
        });
    }
}

// 生命周期钩子
onMounted(() => {
    initAllCharts();
});

onBeforeUnmount(() => {
    disposeCharts();
});
</script>

<style scoped>
.sales-dashboard {
    padding: 20px;
}

.sales-dashboard h1 {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
}

.chart-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    gap: 20px;
}

.chart-card {
    flex: 1;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.chart-container {
    width: 100%;
    height: 350px;
}

@media (max-width: 768px) {
    .chart-row {
        flex-direction: column;
    }

    .chart-card {
        margin-bottom: 20px;
    }
}
</style>